package com.suneee.permission.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.suneee.base.util.ContextHelper;
import com.suneee.core.error.Assert;
import com.suneee.core.error.ErrorUtils;
import com.suneee.core.util.StringUtils;
import com.suneee.permission.bean.PermissionDto;
import com.suneee.permission.dao.PermissionDao;
import com.suneee.permission.entity.Permission;
import com.suneee.permission.service.PermissionService;
import com.suneee.resources.ProductError;
import com.suneee.role.dao.RoleDao;

@Service("api-permissionService")
public class PermissionServiceImpl implements PermissionService {

	@Autowired
	private PermissionDao permissionDao;
	
	@Autowired
	private RoleDao roleDao;
	
	@Override
	public void add(Permission permission) 
	{
		Assert.notNull(permission, "菜单配置值");
		Assert.notEmpty(permission.getName(), "菜单/按钮/功能名称");
		Assert.notEmpty(permission.getGroupName(), "未指定添加的菜单/功能/链接是平台端还是企业端");
		int codeLen = 0;
		//获取创建人
		String userName = ContextHelper.getCurrentLoginInfo().getName();
		
		//获取父类编码isExitsUpdateName
		String parentCode = permission.getParentCode();
		boolean isFlag = permissionDao.isExitsMenuName(permission);
		if(isFlag)
		{
			throw ErrorUtils.wrap(ProductError.MENU_PERMISSION_NAME);
		}

		boolean isUrlExitFlag = permissionDao.isExitsUrl(permission);
		if(isUrlExitFlag)
		{
			throw ErrorUtils.wrap(ProductError.MENU_PERMISSION_URL);
		}
	
		//获取父类编码长度判断
		if(StringUtils.isEmpty(parentCode))
		{
			//父类编码为空将其置于“” 方便后续进行CODE 拼接
			parentCode = "";
			codeLen = 2;
		}
		else
		{
			codeLen = parentCode.length()+2;
		}
		String maxCode = permissionDao.getMaxCode(codeLen,parentCode);
		String childCode = this.createCode(maxCode, codeLen/2);
		childCode = childCode.substring(childCode.length()-2,childCode.length());
		permission.setCode(parentCode+childCode);
		permission.setCreateUser(userName);
		permission.setCreateTime(new Timestamp(System.currentTimeMillis()));
		permission.setUpdateUser(userName);
		permission.setUpdateTime(new Timestamp(System.currentTimeMillis()));
		permission.setOrderNum(0);
		permissionDao.insert(permission);
		
		
		List<Integer> list = new ArrayList<Integer>();
		list.add(permission.getPermissionId());
		Integer roleId = null;
		if("pt".equals(permission.getGroupName()))
		{
			
			List<Map<String,Object>> ptlist = permissionDao.queryForList("select role_id from t_role where name = ? ", "管理员");
			if(null != ptlist && ptlist.size() > 0)
			{
				roleId = (Integer)ptlist.get(0).get("role_id");	
			}
			else
			{
				roleId = 1;
			}
			
		}
		else
		{
			List<Map<String,Object>> enlist = permissionDao.queryForList("select role_id from t_role where name = ? ", "public_roles");
			if(null != enlist && enlist.size() > 0)
			{
				roleId = (Integer)enlist.get(0).get("role_id");	
			}
			else
			{
				roleId = 2;
			}
		}
		//2为public_role角色的ID 
		roleDao.authorizedPermission(roleId, list);
	}

	@Override
	public void delete(Integer permissionId,String code,String groupName) 
	{
		Assert.notNull(permissionId, "菜单/按钮/功能ID");
		Assert.notEmpty(code, "菜单/按钮/功能编码");
		boolean isFlag = permissionDao.isExitsChildMenu( permissionId,code);
		if(isFlag)
		{
			throw ErrorUtils.wrap(ProductError.MENU_PERMISSION_HAVING_CHILD);
		}
		
		List<Integer> list = new ArrayList<Integer>();
		list.add(permissionId);
		Integer roleId = null;
		if("pt".equals(groupName))
		{
			
			List<Map<String,Object>> ptlist = permissionDao.queryForList("select role_id from t_role where name = ? ", "管理员");
			if(null != ptlist && ptlist.size() > 0)
			{
				roleId = (Integer)ptlist.get(0).get("role_id");	
			}
			else
			{
				roleId = 1;
			}
			
		}
		else
		{
			List<Map<String,Object>> enlist = permissionDao.queryForList("select role_id from t_role where name = ? ", "public_roles");
			if(null != enlist && enlist.size() > 0)
			{
				roleId = (Integer)enlist.get(0).get("role_id");	
			}
			else
			{
				roleId = 2;
			}
		}
		roleDao.deleteRelationBySQL(roleId,list);
		
		permissionDao.delete(permissionId);
		
	}
	

	@Override
	public List<Permission> permissionList(PermissionDto dto) {

		if(dto == null){
			dto = new PermissionDto();
		}
		//获取一级菜单
		List<Permission> oneList = permissionDao.permissionNewList(2,null,dto.getGroupName());
		if( null != oneList && oneList.size() > 0)
		{
			for(Permission one:oneList)
			{
				one.setLevel(1);
				//获取二级菜单
				List<Permission> twoList = permissionDao.permissionNewList(4,one.getCode(),dto.getGroupName());
				if(null != twoList && twoList.size() > 0)
				{
					for(Permission two:twoList)
					{
						two.setLevel(2);
						//获取三级菜单
						List<Permission> threeList = permissionDao.permissionNewList(6,two.getCode(),dto.getGroupName());
						if(null != threeList && threeList.size() > 0)
						{
							for(Permission three:threeList)
							{
								three.setLevel(3);
								//获取四级菜单
								List<Permission> fourList = permissionDao.permissionNewList(8,three.getCode(),dto.getGroupName());
								if(null != fourList && fourList.size() > 0)
								{
									for(Permission four:fourList)
									{
										four.setLevel(4);
										//获取五级菜单
										List<Permission> fiveList = permissionDao.permissionNewList(10,four.getCode(),dto.getGroupName());
										if(null != fiveList && fiveList.size() > 0)
										{
											for(Permission five:fiveList)
											{
												five.setLevel(5);
											}
											four.setChildren(fiveList);
										}
									}
									three.setChildren(fourList);
								}
							}
							two.setChildren(threeList);
						}
					}
					one.setChildren(twoList);
				}
			}
		}
		return oneList;
	}

	@Override
	public List<Permission> notUsedPermissionList(Integer roleId) {
		
//		String enterpriseCode = "suneee";
		String enterpriseCode = ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode();
		
		return permissionDao.notUsedPermissionList(roleId,enterpriseCode);
	}
	
	// 创建新的编码
		public String createCode(String maxCode, int level)
		{
				String CODE_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
				if (maxCode == null || maxCode.length() == 0) {
					return "01";
				}
				int f1 = 0;
				int f2 = -1;
				String ret;
				String superCode = maxCode;
				if (maxCode.length() >= level * 2) {
					superCode = maxCode.substring(0, (level - 1) * 2);
					String curChild = maxCode.substring((level - 1) * 2);
					f1 = CODE_CHARS.indexOf(curChild.charAt(0));
					f2 = CODE_CHARS.indexOf(curChild.charAt(1));

				} else {
					superCode = maxCode.substring(0, (level - 1) * 2);
				}
				f2++;
				if (f2 == CODE_CHARS.length()) {
					f1++;
					f2 = 0;
					if (f1 == CODE_CHARS.length()) {
						throw ErrorUtils.wrap(ProductError.CODING_IS_NOT_ENOUGH);
					}
				}
				ret = superCode + CODE_CHARS.charAt(f1) + CODE_CHARS.charAt(f2);

				return ret;

			}

		@Override
		public void update(Permission permission) 
		{
			Assert.notNull(permission.getShowType(), "类型");
			Assert.notNull(permission.getName().trim(), "菜单/功能名称");
			Assert.notNull(permission.getEnabled(), "是否可用");
			Permission per= permissionDao.select(permission.getPermissionId());
			if(null == per)
			{
				throw ErrorUtils.wrap(ProductError.MENU_PERMISSION_NOTEXITS);
			}
			per.setName(permission.getName());
			per.setEnabled(permission.getEnabled());
			per.setUri(permission.getUri());
			per.setIcon(permission.getIcon());
			
			boolean isUrlExitFlag = permissionDao.isExitsUrl(permission);
			if (isUrlExitFlag) {
				throw ErrorUtils.wrap(ProductError.MENU_PERMISSION_URL);
			}
			
			boolean isFlag = permissionDao.isExitsUpdateName(per);
			if(isFlag)
			{
				throw ErrorUtils.wrap(ProductError.MENU_PERMISSION_NAME);
			}
			permissionDao.update(per);
			
			//禁用父类菜单。 其对应的子菜单也一并禁用
			/*if(null != permission.getEnabled() && 0 == permission.getEnabled())
			{
				Permission pn = permissionDao.select(permission.getPermissionId());
				if(null != pn)
				{
					Object [] args = new Object[1];
					args[0] = pn.getGroupName();
					args[1] = pn.getCode() + "%";
					permissionDao.executeUpdate("update t_permission set enabled = 0 where group_name = ? code like ?", args);	
				}
				
			}*/
		}

		@Override
		public void enable(Permission permission) 
		{
			permissionDao.enable(permission);
		}

		@Override
		public Map<String,Integer> isMenuChildren(String code) 
		{
			Assert.notEmpty(code, "菜单/按钮/功能编码");
			code = code + "%";
			Map<String,Integer> resultMap = new HashMap<String,Integer>();
			
			//查询某一个菜单下是否有菜单
			List<Map<String,Object>> childList = permissionDao.queryForList("select * from t_permission where show_type = 1 and code like ? ", code);
			
			//查询某一菜单下是否有功能/按钮/链接
			List<Map<String,Object>> childrenList = permissionDao.queryForList("select * from t_permission where show_type != 1 and code like ? ", code);
			if(null != childList && childList.size() > 1)
			{
				resultMap.put("isChildren", 1);
			}
			else
			{
				if(null != childrenList && childrenList.size() > 0)
				{
					resultMap.put("isChildren", 2);
				}
				else
				{
					resultMap.put("isChildren", 0);	
				}
				
			}
			return resultMap;
		}

		@Override
		public Permission querySiglePerMissionInfo(Permission permission) 
		{
			Assert.notNull(permission, "菜单数据");
			Assert.notNull(permission.getPermissionId(), "菜单ID");
			Permission reultPer = permissionDao.select(permission.getPermissionId());
			if(null != reultPer && !StringUtils.isEmpty(reultPer.getParentCode()))
			{
				List<Permission> list = permissionDao.selectWhere(" code = ?", reultPer.getParentCode());
				if(null != list && list.size() > 0)
				{
					reultPer.setParentName(list.get(0).getName());
				}
			}
			return reultPer;
		}

		@Override
		public void initRolePermissionInfo() {
			//初始化 t_role_permission数据
			
			permissionDao.executeUpdate("delete from t_role_permission where 1 = ?", 1);
			
			//获取平台端管理员角色ID
			List<Map<String,Object>> adminList = permissionDao.queryForList("select role_id from t_role where name = ? ", "管理员");
			
			//获取平台端菜单项
			List<Map<String,Object>> ptMap = permissionDao.queryForList("select permission_id from t_permission where group_name = ? ", "pt");
			List<Integer> ptList = new ArrayList<Integer>();
			for(Map<String,Object> map:ptMap)
			{
				ptList.add(Integer.parseInt(map.get("permission_id").toString()));	
			}
			roleDao.authorizedPermission(Integer.parseInt(adminList.get(0).get("role_id").toString()), ptList);
			
			//获取企业端管理员角色ID
			List<Map<String,Object>> publicList = permissionDao.queryForList("select role_id from t_role where name = ?", "public_roles");
			//获取企业端菜单项
			List<Map<String,Object>> enMap = permissionDao.queryForList("select permission_id from t_permission where group_name = ? ", "en");
			
			List<Integer> enList = new ArrayList<Integer>();
			for(Map<String,Object> map:enMap)
			{
				enList.add(Integer.parseInt(map.get("permission_id").toString()));	
			}
			roleDao.authorizedPermission(Integer.parseInt(publicList.get(0).get("role_id").toString()), enList);
			
			
			
			
		}
}
